package com.sunfeng.chap2.p13;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

/**
 * @Author : 孙峰
 * @Description: 验证AsynchronousCloseException异常的发生
 * <p>
 * 这个实验达不到书中所要的效果
 * @Date : 2021/10/9  15:44
 */

public class Test13_3 {

    private static FileOutputStream fileOutputStream;
    private static FileChannel fileChannelA;

    public static void main(String[] args) throws IOException, InterruptedException {
        fileOutputStream = new FileOutputStream(new File("d:\\nio\\a.txt"));
        fileChannelA = fileOutputStream.getChannel();

        Thread threadA = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("fileChannelA 加锁");
                    fileChannelA.lock(1, 2, false);
                    System.out.println("fileChannelA 解锁");

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread threadB = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("线程B执行了~~~ 关闭开始");
                    fileChannelA.close();
                    System.out.println("线程B执行了~~~ 关闭结束");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        threadA.start();
        Thread.sleep(1);
        threadB.start();
        Thread.sleep(1000);
        fileChannelA.close();
        fileOutputStream.close();
    }

}
